package com.dormitory.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.dormitory.application.MyApplication;
import com.dormitory.bean.UserBean;
import com.dormitory.controller.UserController;
import com.dormitory.httpHelper.HttpLogin;

import org.json.JSONException;

import java.io.IOException;

public class InitActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Context con = getApplicationContext();
        SharedPreferences sp = con.getSharedPreferences("login", MODE_PRIVATE);
        boolean autoLogin = sp.getBoolean("autoLogin", false);
        if(!autoLogin) {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
        else {
            String name = sp.getString("name", "");
            String password = sp.getString("password", "");
            LoginAsyncTask asyncTask = new LoginAsyncTask();
            asyncTask.execute(name, password);
            /*Intent intent = new Intent(this, FilePassActivity.class);
            startActivity(intent);
            finish();*/
        }
    }
    private class LoginAsyncTask extends AsyncTask<String, Object, Object> {

        private UserBean user;
        @Override
        protected Object doInBackground(String[] params) {
            UserController userController = UserController.getInstance();
            user = new UserBean();
            int code = userController.checkUser(params[0], params[1], user);
            if(code == 0) {
                ((MyApplication)getApplication()).setUser(user);
                Intent intent = new Intent(InitActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
            else {
                Intent intent = new Intent(InitActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();
            }
            /*else if(code == 1) {
                Toast.makeText(InitActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
            }
            else {
                Toast.makeText(InitActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
            }*/
            return null;
        }
    }
}
